package com.qianshui.co.medical.admin.user;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.ws.rs.QueryParam;

import org.apache.commons.lang.time.DateUtils;
import org.omg.DynamicAny.DynArrayOperations;

import net.sf.ehcache.writer.writebehind.operations.DeleteAllOperation;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.qianshui.co.medical.common.CommonJson;
import com.qianshui.co.medical.common.DateFormater;
import com.qianshui.co.medical.common.IDOperation;
import com.qianshui.co.medical.db.AdminPermission;
import com.qianshui.co.medical.db.AdminRole;
import com.qianshui.co.medical.db.AdminUser;
import com.qianshui.co.medical.db.Area;
import com.qianshui.co.medical.db.Arrange;
import com.qianshui.co.medical.db.DaoFactory;
import com.qianshui.co.medical.db.DaoFactory.TableName;
import com.qianshui.co.medical.db.Department;
import com.qianshui.co.medical.db.Doctor;
import com.qianshui.co.medical.db.Hospital;
import com.qianshui.co.medical.db.Knowledgeclass;
import com.qianshui.co.medical.db.Knowledgeitem;
import com.qianshui.co.medical.db.Msg;
import com.qianshui.co.medical.db.News;
import com.qianshui.co.medical.db.PregnantKnowledge;

public class AdminUserOperater {
	private static AdminUserOperater m_Instance = null;

	private AdminUserOperater() {

	}

	public static AdminUserOperater getInstance() {
		if (m_Instance == null) {
			m_Instance = new AdminUserOperater();
		}

		return m_Instance;
	}

	public AdminUser login(String loginname, String password) {

		List<AdminUser> list = DaoFactory
				.getInstance()
				.getAdminUser_dao()
				.findByProperty(new String[] { "loginname", "password" },
						new String[] { loginname, password });
		if (list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	public boolean addUser(String loginname, String username, String password,String hospitalid) {

		AdminUser user = new AdminUser(loginname, password, username, hospitalid);
		DaoFactory.getInstance().getAdminUser_dao().save(user);

		return false;
	}

	public boolean deleteUser(String id) {
		return false;
	}

	public List<AdminUser> findAllAdmin() {
		List<AdminUser> list = DaoFactory.getInstance().getAdminUser_dao()
				.findAll("id", true);
		return list;
	}

	public List<AdminPermission> findAllPermission() {
		List<AdminPermission> MenuList = new ArrayList<AdminPermission>();
		List<AdminPermission> list = DaoFactory.getInstance()
				.getAdminPermission_dao()
				.query("select p.* from admin_permission p where p.leaf=0");

		if (list != null) {
			Iterator it = list.iterator();
			while (it.hasNext()) {
				AdminPermission Temp = (AdminPermission) it.next();

				MenuList.add(findChildNode(Temp));
			}
		}

		return MenuList;
	}

	private AdminPermission findChildNode(AdminPermission item) {

		List<AdminPermission> rs = DaoFactory
				.getInstance()
				.getAdminPermission_dao()
				.query("select p.* from admin_permission p where p.perid='"
						+ item.getId() + "'");
		// Transaction tx = session.beginTransaction();
		if (rs != null) {
			Iterator<AdminPermission> temp = rs.iterator();
			while (temp.hasNext()) {
				AdminPermission cate = (AdminPermission) temp.next();
				if (cate.getLeaf() != null && cate.getLeaf() == 1) {
					item.setChildren(cate);
				} else {
					item.setChildren(findChildNode(cate));
				}
			}
		}
		return item;
	}

	public List<AdminRole> findAllRole() {
		List<AdminRole> list = DaoFactory.getInstance().getAdminRole_dao()
				.findAll("id", true);
		return list;
	}

	public List<AdminPermission> getMenuList(String userid) {
		List<AdminPermission> MenuList = new ArrayList<AdminPermission>();
		List<AdminPermission> list = DaoFactory
				.getInstance()
				.getAdminPermission_dao()
				.query("select p.* from admin_permission p,lnk_role_permission r,lnk_role_user u "
						+ "where r.permissionid=p.id and u.roleid=r.roleid and u.userid="
						+ userid);

		if (list != null) {
			Iterator it = list.iterator();
			while (it.hasNext()) {

				AdminPermission Temp = (AdminPermission) it.next();
				List<AdminPermission> rs = DaoFactory
						.getInstance()
						.getAdminPermission_dao()
						.query("select p.* from admin_permission p where p.perid='"
								+ Temp.getId() + "'");

				if (rs != null) {
					Iterator item = rs.iterator();
					while (item.hasNext()) {
						Temp.setChildren((AdminPermission) item.next());
					}
				}
				MenuList.add(Temp);
			}
		}

		return MenuList;
	}

	public List<Knowledgeclass> buildKnowledgeTree() {
		List<Knowledgeclass> ClassList = new ArrayList<Knowledgeclass>();
		List<Knowledgeclass> list = DaoFactory.getInstance()
				.getKnowledgeclass_dao()
				.query("select p.* from knowledgeclass p where p.parentid='0'");

		if (list != null) {
			Iterator it = list.iterator();
			while (it.hasNext()) {
				Knowledgeclass Temp = (Knowledgeclass) it.next();

				ClassList.add(findKnowledgeItem(Temp));
			}
		}

		return ClassList;
	}

	private Knowledgeclass findKnowledgeItem(Knowledgeclass item) {

		List<Knowledgeclass> rs = DaoFactory
				.getInstance()
				.getKnowledgeclass_dao()
				.query("select p.* from knowledgeclass p where p.parentid='"
						+ item.getId() + "'");
		// Transaction tx = session.beginTransaction();
		if (rs != null) {
			Iterator<Knowledgeclass> temp = rs.iterator();
			while (temp.hasNext()) {
				Knowledgeclass cate = (Knowledgeclass) temp.next();

				item.setChildren(findKnowledgeItem(cate));
			}
		}
		return item;
	}

	/***************************************************************************************************************************
	 * Arrange Operations
	 * 
	 * @param departmentid
	 * @param startday
	 * @param endday
	 * @return
	 */
	public List<Map<String, Object>> queryArrange(String departmentid,
			String startday, String endday) {
		List<Doctor> doc_list = DaoFactory.getInstance().getDoctor_dao()
				.findByProperty("departmentid", departmentid);
		List<Map<String, Object>> map_list = new ArrayList<Map<String, Object>>();
		for (Doctor doc : doc_list) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("doctor_id", doc.getId());
			map.put("doctor_name", doc.getName());
			Date start = DateFormater.getDateByShortZHString(startday);
			Date end = DateFormater.getDateByShortZHString(endday);

			while (start.compareTo(end) < 1) {
				map.put(DateFormater.formatZHShortDate(start), 3);
				Calendar calendar = new GregorianCalendar();
				calendar.setTime(start);
				calendar.add(calendar.DATE, 1);// 把日期往后增加一天.整数往后推,负数往前移动
				start = calendar.getTime();
			}

			List<Arrange> list = DaoFactory
					.getInstance()
					.getArrange_dao()
					.query("select a.* from arrange a where " + "a.doctorid='"
							+ doc.getId() + "' and a.orderdate between '"
							+ startday + "' and '" + endday + "'");

			for (Arrange arr : list) {
				if (map.containsKey(DateFormater.formatZHShortDate(arr
						.getOrderdate()))) {
					map.put(DateFormater.formatZHShortDate(arr.getOrderdate()),
							arr.getType());
				}
			}

			map_list.add(map);
		}
		return map_list;

	}

	public void saveArrange(String json) {
		@SuppressWarnings("unchecked")
		List<Map<String, String>> map_list = (List<Map<String, String>>) new Gson()
				.fromJson(json, new TypeToken<List<Map<String, String>>>() {
				}.getType());
		if (map_list != null && map_list.size() > 0) {
			for (Map<String, String> pair : map_list) {
				String doc_id = pair.get("doctor_id").toString();
				Iterator<Entry<String, String>> iter = pair.entrySet()
						.iterator();

				Entry<String, String> entry;

				while (iter.hasNext()) {

					entry = iter.next();
					String key = entry.getKey();

					String value = entry.getValue();
					if (value.equals("3"))
						continue;
					if (!key.equals("doctor_name") && !key.equals("doctor_id")) {
						List<Arrange> list = DaoFactory
								.getInstance()
								.getArrange_dao()
								.findByProperty(
										new String[] { "doctorid", "orderdate" },
										new Object[] {
												doc_id,
												DateFormater
														.getDateByShortZHString(key) });

						if (list != null && list.size() > 0) {
							Arrange temp = list.get(0);
							temp.setType(Integer.parseInt(value.toString()));
							DaoFactory.getInstance().getArrange_dao()
									.update(temp);
						} else {
							Arrange arrange = new Arrange();
							arrange.setDoctorid(doc_id);
							arrange.setOrderdate(DateFormater
									.getDateByShortZHString(key));
							arrange.setType(Integer.parseInt(value));
							arrange.setId(IDOperation.getClassID(arrange
									.getClass().getName()));
							DaoFactory.getInstance().getArrange_dao()
									.save(arrange);
						}
					}

				}
			}
		}
	}

	/***************************************************************************************************************************/

	public Object addOrUpdateRecord(String table, String json) {
		Object obj = null;
		switch (DaoFactory.TableName.valueOf(table)) {
		case AdminPermission:
			AdminPermission temp = (AdminPermission) CommonJson.Json2Obj(json,
					AdminPermission.class);
			if (temp != null) {
				if (temp.getId() == null || temp.getId().equals("")) {
					temp.setId(IDOperation
							.getClassID(temp.getClass().getName()));
					if (DaoFactory.getInstance().getAdminPermission_dao()
							.save(temp)) {
						obj = temp;
					}
				} else {
					if (DaoFactory.getInstance().getAdminPermission_dao()
							.update(temp)) {
						obj = temp;
					}
				}

			}
			break;
		case AdminRole:
			AdminRole temp1 = (AdminRole) CommonJson.Json2Obj(json,
					AdminRole.class);
			if (temp1 != null) {
				DaoFactory.getInstance().getAdminRole_dao().saveOrUpdate(temp1);
				obj = temp1;

			}
			break;
		case AdminUser:
			AdminUser temp11 = (AdminUser) CommonJson.Json2Obj(json,
					AdminUser.class);
			if (temp11 != null) {
				DaoFactory.getInstance().getAdminUser_dao()
						.saveOrUpdate(temp11);
				obj = temp11;

			}
			break;
		case Area:
			Area temp_Area = (Area) CommonJson.Json2Obj(json, Area.class);
			if (temp_Area != null) {
				if (temp_Area.getId() == null || temp_Area.getId().equals("")) {
					temp_Area.setId(IDOperation.getClassID(temp_Area.getClass()
							.getName()));
					if (DaoFactory.getInstance().getArea_dao().save(temp_Area)) {
						obj = temp_Area;
					}
				} else {
					if (DaoFactory.getInstance().getArea_dao()
							.update(temp_Area)) {
						obj = temp_Area;
					}
				}
			}
			break;
		case Arrange:
			break;
		case Category:
			break;
		case Doctor:
			Doctor temp_Doctor = (Doctor) CommonJson.Json2Obj(json,
					Doctor.class);
			if (temp_Doctor != null) {
				if (temp_Doctor.getId() == null
						|| temp_Doctor.getId().equals("")) {
					temp_Doctor.setId(IDOperation.getClassID(temp_Doctor
							.getClass().getName()));
					if (DaoFactory.getInstance().getDoctor_dao()
							.save(temp_Doctor)) {
						obj = temp_Doctor;
					}
				} else {
					if (DaoFactory.getInstance().getDoctor_dao()
							.update(temp_Doctor)) {
						obj = temp_Doctor;
					}
				}
			}
			break;
		case News:
			News temp_News = (News) CommonJson.Json2Obj(json, News.class);
			if (temp_News != null) {
				if (temp_News.getId() == null || temp_News.getId().equals("")) {
					temp_News.setId(IDOperation.getClassID(temp_News.getClass()
							.getName()));
					temp_News
							.setCreatedate(DateFormater
									.getTimestampByString(DateFormater
											.formatLongDateTime(new Date())));
					if (DaoFactory.getInstance().getNews_dao().save(temp_News)) {
						obj = temp_News;
					}
				} else {
					if (DaoFactory.getInstance().getNews_dao()
							.update(temp_News)) {
						obj = temp_News;
					}
				}
			}
			break;
		case Department:
			Department temp_Department = (Department) CommonJson.Json2Obj(json,
					Department.class);
			if (temp_Department != null) {
				if (temp_Department.getId() == null
						|| temp_Department.getId().equals("")) {
					temp_Department.setId(IDOperation
							.getClassID(temp_Department.getClass().getName()));
					if (DaoFactory.getInstance().getDepartment_dao()
							.save(temp_Department)) {
						obj = temp_Department;
					}
				} else {
					if (DaoFactory.getInstance().getDepartment_dao()
							.update(temp_Department)) {
						obj = temp_Department;
					}
				}
			}
			break;
		case Hospital:
			Hospital temp_Hospital = (Hospital) CommonJson.Json2Obj(json,
					Hospital.class);
			if (temp_Hospital != null) {
				if (temp_Hospital.getId() == null
						|| temp_Hospital.getId().equals("")) {
					temp_Hospital.setId(IDOperation.getClassID(temp_Hospital
							.getClass().getName()));
					if (DaoFactory.getInstance().getHospital_dao()
							.save(temp_Hospital)) {
						obj = temp_Hospital;
					}
				} else {
					if (DaoFactory.getInstance().getHospital_dao()
							.update(temp_Hospital)) {
						obj = temp_Hospital;
					}
				}
			}
			break;
		case Replay:
			break;
		case Score:
			break;
		case Threads:
			break;
		case Trace:
			break;
		case User:
			break;
		case Userinfo:
			break;
		case Knowledgeclass:
			Knowledgeclass temp_Knowledgeclass = (Knowledgeclass) CommonJson.Json2Obj(json,
					Knowledgeclass.class);
			if (temp_Knowledgeclass != null) {
				if (temp_Knowledgeclass.getId() == null
						|| temp_Knowledgeclass.getId().equals("")) {
					temp_Knowledgeclass.setId(IDOperation.getClassID(temp_Knowledgeclass
							.getClass().getName()));
					if (DaoFactory.getInstance().getKnowledgeclass_dao()
							.save(temp_Knowledgeclass)) {
						obj = temp_Knowledgeclass;
					}
				} else {
					if (DaoFactory.getInstance().getKnowledgeclass_dao()
							.update(temp_Knowledgeclass)) {
						obj = temp_Knowledgeclass;
					}
				}
			}
			break;
		case Knowledgeitem:
			Knowledgeitem temp_Knowledgeitem = (Knowledgeitem) CommonJson.Json2Obj(json,
					Knowledgeitem.class);
			if (temp_Knowledgeitem != null) {
				if (temp_Knowledgeitem.getId() == null
						|| temp_Knowledgeitem.getId().equals("")) {
					temp_Knowledgeitem.setId(IDOperation.getClassID(temp_Knowledgeitem
							.getClass().getName()));
					if (DaoFactory.getInstance().getKnowledgeitem_dao()
							.save(temp_Knowledgeitem)) {
						obj = temp_Knowledgeitem;
					}
				} else {
					if (DaoFactory.getInstance().getKnowledgeitem_dao()
							.update(temp_Knowledgeitem)) {
						obj = temp_Knowledgeitem;
					}
				}
			}
			
			break;
		case Msg:
			Msg temp_Msg = (Msg) CommonJson.Json2Obj(json,
					Msg.class);
			if (temp_Msg != null) {
				if (temp_Msg.getId() == null
						) {
					temp_Msg
					.setCreatedate(DateFormater
							.getTimestampByString(DateFormater
									.formatLongDateTime(new Date())));
					if (DaoFactory.getInstance().getMsg_dao()
							.save(temp_Msg)) {
						obj = temp_Msg;
					}
				} else {
					if (DaoFactory.getInstance().getMsg_dao()
							.update(temp_Msg)) {
						obj = temp_Msg;
					}
				}
			}
			
			break;
		case PregnantKnowledge:
			PregnantKnowledge temp_PregnantKnowledge = (PregnantKnowledge) CommonJson.Json2Obj(json,
					PregnantKnowledge.class);
			if (temp_PregnantKnowledge != null) {
				if (temp_PregnantKnowledge.getId() == null
						) {
					temp_PregnantKnowledge
					.setCreatedate(DateFormater
							.getTimestampByString(DateFormater
									.formatLongDateTime(new Date())));
					if (DaoFactory.getInstance().getPregnantKnowledge_dao()
							.save(temp_PregnantKnowledge)) {
						obj = temp_PregnantKnowledge;
					}
				} else {
					if (DaoFactory.getInstance().getPregnantKnowledge_dao()
							.update(temp_PregnantKnowledge)) {
						obj = temp_PregnantKnowledge;
					}
				}
			}
			break;
		}

		return obj;
	}

	public boolean deleteRecord(String table, String json) {
		Object obj = null;
		switch (DaoFactory.TableName.valueOf(table)) {
		case AdminPermission:
			AdminPermission temp = (AdminPermission) CommonJson.Json2Obj(json,
					AdminPermission.class);
			if (temp != null) {
				return DaoFactory.getInstance().getAdminPermission_dao()
						.delete(temp);
			}
			break;
		case AdminRole:
			AdminRole temp1 = (AdminRole) CommonJson.Json2Obj(json,
					AdminRole.class);
			if (temp1 != null) {
				return DaoFactory.getInstance().getAdminRole_dao()
						.delete(temp1);

			}
			break;
		case AdminUser:
			AdminUser temp11 = (AdminUser) CommonJson.Json2Obj(json,
					AdminUser.class);
			if (temp11 != null) {
				return DaoFactory.getInstance().getAdminUser_dao()
						.delete(temp11);
			}
			break;
		case Area:
			Area temp_Area = (Area) CommonJson.Json2Obj(json, Area.class);
			if (temp_Area != null) {
				return DaoFactory.getInstance().getArea_dao().delete(temp_Area);
			}
			break;
		case Arrange:
			break;
		case Category:
			break;
		case Doctor:
			Doctor temp_Doctor = (Doctor) CommonJson.Json2Obj(json,
					Doctor.class);
			if (temp_Doctor != null) {
				return DaoFactory.getInstance().getDoctor_dao()
						.delete(temp_Doctor);

			}
			break;
		case News:
			News temp_News = (News) CommonJson.Json2Obj(json, News.class);
			if (temp_News != null) {
				return DaoFactory.getInstance().getNews_dao().delete(temp_News);
			}
			break;
		case Department:
			Department temp_Department = (Department) CommonJson.Json2Obj(json,
					Department.class);
			if (temp_Department != null) {
				return DaoFactory.getInstance().getDepartment_dao()
						.delete(temp_Department);
			}
			break;
		case Hospital:
			Hospital temp_Hospital = (Hospital) CommonJson.Json2Obj(json,
					Hospital.class);
			if (temp_Hospital != null) {
				return DaoFactory.getInstance().getHospital_dao()
						.delete(temp_Hospital);
			}
			break;
		case Replay:
			break;
		case Score:
			break;
		case Threads:
			break;
		case Trace:
			break;
		case User:
			break;
		case Userinfo:
			break;
		case Knowledgeclass:
			Knowledgeclass temp_Knowledgeclass = (Knowledgeclass) CommonJson.Json2Obj(json,
					Knowledgeclass.class);
			if (temp_Knowledgeclass != null) {
				return DaoFactory.getInstance().getKnowledgeclass_dao()
						.delete(temp_Knowledgeclass);
			}
			break;
		case Msg:
			Msg temp_Msg = (Msg) CommonJson.Json2Obj(json,
					Msg.class);
			if (temp_Msg != null) {
				return DaoFactory.getInstance().getMsg_dao()
						.delete(temp_Msg);
			}
			break;
		case PregnantKnowledge:
			PregnantKnowledge temp_PregnantKnowledge = (PregnantKnowledge) CommonJson.Json2Obj(json,
					PregnantKnowledge.class);
			if (temp_PregnantKnowledge != null) {
				return DaoFactory.getInstance().getPregnantKnowledge_dao()
						.delete(temp_PregnantKnowledge);
			}
			break;
		}
		return false;

	}

}
